﻿using KouDai.Core.Helper;
using System.IO;
using System.Threading;
using System.Threading.Tasks;

namespace KouDai.Core.Engine
{
    public class ServiceFileEngine : INetEngine
    {
        public async Task RequestAsync(CommunicationData commnunicationData)
        {
            await RequestAsync(commnunicationData, CancellationToken.None);
        }

        public async Task RequestAsync(CommunicationData commnunicationData,CancellationToken cancellationToken)
        {
            string imageUrl = commnunicationData.SendData.ImageUrl;
            BackData backData = commnunicationData.BackData;
            //判断本地是否包含图片，1.如果包含则直接读取2.如果不包含则请求

            //await ReadImageDataFromCache(imageUrl);
            Stream imageDataStream = null;
            if (imageDataStream != null)
            {
                backData.ResposeData = imageDataStream;
            }
            else
            {
                HttpEngine _httpEngine = new HttpEngine();
                byte[] imageBytes = await _httpEngine.Request(imageUrl, "GET", "",cancellationToken);
                MemoryStream stream = new MemoryStream(imageBytes);
                backData.ResposeData = stream;
                backData.IsSuccess = true;
            }
        }

        private async Task<Stream> ReadImageDataFromCache(string imageUrl)
        {
            string imageName = GenerateImageNameFromUrl(imageUrl);
            //文件读取
            Stream fileStream = await LocalFileAdapter.Current.LoadFileAsync(Constants.ImageFolderName,imageName);
            return fileStream;
        }

        private string GenerateImageNameFromUrl(string imageUrl)
        {
            string realImageName = imageUrl.Substring(imageUrl.LastIndexOf("/") + 1);
            string md5ImageName = MD5CryptoServiceProvider.GetMd5String(realImageName) + Path.GetExtension(realImageName);
            return md5ImageName;
        }

    }
}
